package com.service.purchase;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.excel.EasyExcel;
import com.common.DateUtils;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.dao.purchase.ContractChangeDao;
import com.dao.purchase.OrderChangeDao;
import com.dao.purchase.OrderChangeMmDao;
import com.dao.purchase.OrderChangeSupplyDao;
import com.dao.purchase.OrderDao;
import com.dao.purchase.PlanMmMapper;
import com.dao.purchase.SupplyDealMapper;
import com.dao.purchase.SupplyDealMmMapper;
import com.dao.supply.InfoMapper;
import com.enums.WorkFlowIdModel;
import com.model.external.oa.OaWorkFlowResult;
import com.model.purchase.ContractChangeModel;
import com.model.purchase.ContractModel;
import com.model.purchase.OrderChangeMmModel;
import com.model.purchase.OrderChangeModel;
import com.model.purchase.OrderChangeSupplyModel;
import com.model.purchase.OrderChangeVoModel;
import com.model.purchase.OrderModel;
import com.model.purchase.PurchaseInquiryResult;
import com.model.purchase.PurchasePlanMm;
import com.model.purchase.PurchaseSupplyDeal;
import com.model.purchase.PurchaseSupplyDealMm;
import com.model.purchase.PurchaseSupplyDealVoModel;
import com.model.supply.SupplyInfoModel;
import com.model.sys.SysUser;
import com.service.external.oa.ContractChangeOaService;
import com.service.external.oa.CreateContractService;
import com.service.external.oa.GetWFStatusService;
import com.service.external.sap.SapPurchaseService;
import com.common.model.Global;
import com.common.spring.SpringMvcUtils;

@Service
public class OrderChangeService {
	static final Logger logger = LoggerFactory.getLogger(OrderChangeService.class);

	@Autowired
	OrderChangeDao orderChangeDao;
	@Autowired
	OrderDao orderDao;
	@Autowired
	OrderChangeSupplyDao orderChangeSupplyDao;
	@Autowired
	OrderChangeMmDao orderChangeMmDao;
	@Autowired
	ContractChangeDao contractChangeDao;
	@Autowired
	GetWFStatusService wfStatusService;
	@Autowired
	InfoMapper infoMapper;
	@Autowired
	ContractChangeOaService createContractService;
	@Autowired
	SapPurchaseService sapPurchaseService;
	@Autowired
	CommonService commonService;
	@Autowired
	PlanMmMapper planMmMapper;
	@Autowired
	SupplyDealMapper supplyDealMapper;
	@Autowired
	SupplyDealMmMapper supplyDealMmMapper;

	/**
	 * 列表查询
	 *
	 * @param queryMap
	 * @return
	 */
	public HttpResult selectList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				queryMap.put("deptIds", sysUser.getDatapermission().split(","));
			} else {
				queryMap.put("createId", sysUser.getUserid());
			}
		}
		List<OrderChangeModel> list = orderChangeDao.selectList(queryMap);
		int count = orderChangeDao.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectList:{}", list);
		return httpResult;
	}

	/**
	 * 详情
	 * 
	 * @param
	 * @return
	 */
	public HttpResult selectInfor(String ordId) {
		HttpResult httpResult = new HttpResult();
		OrderChangeModel orderChangeModel = orderChangeDao.load(ordId);

		OrderChangeVoModel orderChangeVoModel = new OrderChangeVoModel();
		BeanUtils.copyProperties(orderChangeModel, orderChangeVoModel);
		OrderChangeSupplyModel orderChangeSupplyModels = orderChangeSupplyDao.load(ordId, orderChangeModel.getInfId());
		orderChangeVoModel.setOrderChangeSupplyModel(orderChangeSupplyModels);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("ordId", ordId);
		map.put("infId", orderChangeModel.getInfId());
		List<OrderChangeMmModel> orderChangeMmModels = orderChangeMmDao.selectList(map);
		orderChangeVoModel.setOrderChangeMmModels(orderChangeMmModels);

		httpResult.setData(orderChangeVoModel);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	/**
	 * 保存
	 *
	 * @param
	 * @return
	 */
	public HttpResult save(OrderChangeVoModel orderChangeVoModel) {
		if (orderChangeVoModel == null) {
			return HttpResult.error("参数不能为空");
		}

		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!StringUtils.isNotNull(sysUser.getSap())) {
			return HttpResult.error("采购组账号不存在！");
		}
		SupplyInfoModel supplyInfoModel = infoMapper.load(orderChangeVoModel.getInfId());
		orderChangeVoModel.setOrdLegal(supplyInfoModel.getInfLegalPerson());
		orderChangeVoModel.setOrdContractName(supplyInfoModel.getInfContactsName());
		int result = 0;

		result = orderChangeSupplyDao.update(orderChangeVoModel.getOrderChangeSupplyModel());

		int i = 0;
		for (OrderChangeMmModel dealMm : orderChangeVoModel.getOrderChangeMmModels()) {
			PurchasePlanMm programMm = planMmMapper.load(dealMm.getPlanId());
			dealMm.setPlanNedType(programMm.getPlanNedType());
			dealMm.setPlanDeptCode(programMm.getPlanDeptCode());
			dealMm.setPlanCorpCode(programMm.getPlanCorpCode());
			dealMm.setPlanCode(programMm.getPlanCode());
			dealMm.setMmCode(programMm.getMmCode());
			dealMm.setMmDetail(programMm.getMmDetail());
			dealMm.setMmUnit(programMm.getMmUnit());
			dealMm.setMmTypeCode(programMm.getMmTypeCode());
			dealMm.setPlanFactoryCode(programMm.getPlanFactoryCode());
			dealMm.setPlanGoodType(programMm.getPlanGoodType());
			dealMm.setPlanProType(programMm.getPlanProType());
			dealMm.setPlanOrderCode(programMm.getPlanOrderCode());
			dealMm.setPlanMeanCode(programMm.getPlanMeanCode());
			dealMm.setPlanCostCode(programMm.getPlanCostCode());
			dealMm.setPlanNeedDate(programMm.getPlanNeedDate());
			dealMm.setPlanAssessType(
					StringUtils.isNullOrEmpty(programMm.getPlanAssessType()) ? "" : programMm.getPlanAssessType());
			dealMm.setMmMain(programMm.getMmMain());
			dealMm.setMmTypeName(programMm.getMmTypeName());
			dealMm.setPlanCostDetail(programMm.getPlanCostDetail());
			dealMm.setPlanFactoryName(programMm.getPlanFactoryName());
			if (dealMm.getDealNum() == null || dealMm.getDealNum().compareTo(BigDecimal.ZERO) == 0) {

			} else {
				dealMm.setMmRowNum((++i) * 10 + "");
			}
			orderChangeMmDao.update(dealMm);
		}

		// 调用sap生成编码
		if (orderChangeVoModel.getOrdIsSign().equals(Global.NO + "")) {
			OrderChangeSupplyModel orderChangeSupplyModel = orderChangeSupplyDao.load(orderChangeVoModel.getOrdId(),
					orderChangeVoModel.getInfId());
			orderChangeSupplyModel.setInqGroup(sysUser.getSap());
			if (orderChangeVoModel.getOrdCode() != null && orderChangeVoModel.getOrdCode().length() == 16) {
				orderChangeVoModel.setOrdCode("");// 当是否框架从是变为否时
			}
			PurchaseSupplyDeal supplyDeal = new PurchaseSupplyDealVoModel();
			BeanUtils.copyProperties(orderChangeSupplyModel, supplyDeal);
			OrderModel orderModel = new OrderModel();
			BeanUtils.copyProperties(orderChangeVoModel, orderModel);

			List<PurchaseSupplyDealMm> dealMms = new ArrayList<PurchaseSupplyDealMm>();
			for (Iterator iterator = orderChangeVoModel.getOrderChangeMmModels().iterator(); iterator.hasNext();) {
				OrderChangeMmModel tepChangemMmModel = (OrderChangeMmModel) iterator.next();
				PurchaseSupplyDealMm purchaseSupplyDealMm = new PurchaseSupplyDealMm();
				BeanUtils.copyProperties(tepChangemMmModel, purchaseSupplyDealMm);
				dealMms.add(purchaseSupplyDealMm);
			}

			HttpResult sapHttpResult = sapPurchaseService.createSapOrder(supplyDeal, orderModel, dealMms);
			if (sapHttpResult.getCode() == HttpStatus.SUCCESS_CODE) {
				orderChangeVoModel.setOrdCode(sapHttpResult.getData().toString());
				// 修改sap状态
				orderChangeSupplyModel.setInqSapStatus(Global.YES + "");
				result += orderChangeSupplyDao.update(orderChangeSupplyModel);
			} else {
				logger.error(sapHttpResult.getMsg());
				if (sapHttpResult.getMsg().contains("物料")) {
					return HttpResult.error("请联系主数据管理员：" + sapHttpResult.getMsg());
				} else {
					return HttpResult.error("请根据以下错误信息先查找使用手册常见问题：" + sapHttpResult.getMsg());
				}
			}
		} else {
			orderChangeVoModel.setOrdCode(commonService.createCodeSap("purchase_order_change", "ord_code"));
		}

		HttpResult httpResult = new HttpResult();
		if (!StringUtils.isNotNull(orderChangeVoModel.getOrdId())) {
			orderChangeVoModel.setOrdId(UUID.randomUUID().toString());
			result = orderChangeDao.insert(orderChangeVoModel);
		} else {
			result = orderChangeDao.update(orderChangeVoModel);
		}
		if (result > 0) {
			httpResult.setMsg(orderChangeVoModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(orderChangeVoModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(orderChangeVoModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	/**
	 * 提交
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult commit(OrderChangeVoModel orderChangeVoModel) {
		if (orderChangeVoModel == null) {
			return HttpResult.error("参数不能为空");
		}
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!StringUtils.isNotNull(sysUser.getSap())) {
			return HttpResult.error("采购组账号不存在！");
		}
		SupplyInfoModel supplyInfoModel = infoMapper.load(orderChangeVoModel.getInfId());
		orderChangeVoModel.setOrdLegal(supplyInfoModel.getInfLegalPerson());
		orderChangeVoModel.setOrdContractName(supplyInfoModel.getInfContactsName());

		if (orderChangeVoModel.getStatus().equals(Global.YES + "")) {
			// 调用oa接口
			if (orderChangeVoModel.getOrdContractType().equals(Global.YES + "")) {
				HttpResult oaResult = createContractService.CreateContract(orderChangeVoModel, sysUser.getWxid());
				if (oaResult.getCode() != HttpStatus.SUCCESS_CODE) {
					// 强制手动事务回滚
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return HttpResult.error(oaResult.getMsg());
				}
				OaWorkFlowResult oaWorkFlowResult = (OaWorkFlowResult) oaResult.getData();
				orderChangeVoModel.setOaFlowId(oaWorkFlowResult.getOaFlowId());
			}
		}

		orderChangeVoModel.setStatus(Global.YES + "");
		HttpResult httpResult = new HttpResult();
		int result = 0;
		result = orderChangeDao.update(orderChangeVoModel);
		OrderChangeSupplyModel orderChangeSupplyModel = orderChangeSupplyDao.load(orderChangeVoModel.getOrdId(),
				orderChangeVoModel.getInfId());
		orderChangeSupplyModel.setStatus(Global.YES + "");
		result += orderChangeSupplyDao.update(orderChangeSupplyModel);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("ordId", orderChangeVoModel.getOrdId());
		map.put("infId", orderChangeVoModel.getInfId());
		List<OrderChangeMmModel> orderChangeMmModels = orderChangeMmDao.selectList(map);
		for (Iterator iterator = orderChangeMmModels.iterator(); iterator.hasNext();) {
			OrderChangeMmModel orderChangeMmModel = (OrderChangeMmModel) iterator.next();
			orderChangeMmModel.setStatus(Global.YES + "");
			orderChangeMmDao.update(orderChangeMmModel);
		}

		if (result > 0) {
			httpResult.setMsg(orderChangeVoModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(orderChangeVoModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(orderChangeVoModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	/**
	 * 删除
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult delete(String ordId) {
		if (!StringUtils.isNotNull(ordId)) {
			return HttpResult.error("参数不能为空");
		}
		OrderChangeModel model = orderChangeDao.load(ordId);
		if (!model.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("非待提交状态，不可删除！");
		}
		HttpResult httpResult = new HttpResult();
		int result = orderChangeDao.delete(ordId);
		result += orderChangeSupplyDao.delete(ordId, model.getInfId());

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("ordId", ordId);
		map.put("infId", model.getInfId());
		List<OrderChangeMmModel> orderChangeMmModels = orderChangeMmDao.selectList(map);
		for (Iterator iterator = orderChangeMmModels.iterator(); iterator.hasNext();) {
			OrderChangeMmModel orderChangeMmModel = (OrderChangeMmModel) iterator.next();
			orderChangeMmDao.delete(ordId, orderChangeMmModel.getInfId(), orderChangeMmModel.getPlanId());
		}

		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	@Transactional
	public HttpResult createOrder(String ordId) {
		if (!StringUtils.isNotNull(ordId)) {
			return HttpResult.error("参数不能为空！");
		}
//		Map<String, Object> map = new HashMap<String, Object>();
//		List<OrderChangeModel> orderChangeModels = orderChangeDao.selectList(map);
//		if (orderChangeModels.size() == 1) {
//
//		}
		OrderModel orderModel = orderDao.load(ordId);
		if (orderModel == null) {
			return HttpResult.error("此订单不存在！");
		}

		int result = 0;
		// 生成采购订单
		OrderChangeModel orderChangeModel = new OrderChangeModel();
		BeanUtils.copyProperties(orderModel, orderChangeModel);
		orderChangeModel.setOrdId(UUID.randomUUID().toString());
		orderChangeModel.setOrdCode("");
		orderChangeModel.setOrdName("");
		orderChangeModel.setResId(ordId);
		orderChangeModel.setStatus(Global.NO + "");
		orderChangeModel.setOldOrdCode(orderModel.getOrdCode());
		orderChangeModel.setOldOrdName(orderModel.getOrdName());
		orderChangeModel.setCreateTime(DateUtils.getCurrentTime());
		result += orderChangeDao.insert(orderChangeModel);

		PurchaseSupplyDeal supplyDeal = supplyDealMapper.load(orderModel.getResId(), orderModel.getInfId());
		OrderChangeSupplyModel orderChangeSupplyModel = new OrderChangeSupplyModel();
		BeanUtils.copyProperties(supplyDeal, orderChangeSupplyModel);
		orderChangeSupplyModel.setOrdId(orderChangeModel.getOrdId());
		orderChangeSupplyModel.setOrdCode("");
		orderChangeSupplyModel.setOrdName("");
		orderChangeSupplyModel.setStatus(Global.NO + "");
		orderChangeSupplyModel.setResId(ordId);
		orderChangeSupplyModel.setResCode1(orderModel.getOrdCode());
		orderChangeSupplyModel.setCreateTime(DateUtils.getCurrentTime());
		orderChangeSupplyDao.insert(orderChangeSupplyModel);

		List<PurchaseSupplyDealMm> supplyDealMms = supplyDealMmMapper.loadByInfIdAndResId(orderModel.getResId(),
				orderModel.getInfId());
		for (Iterator iterator = supplyDealMms.iterator(); iterator.hasNext();) {
			PurchaseSupplyDealMm purchaseSupplyDealMm = (PurchaseSupplyDealMm) iterator.next();
			OrderChangeMmModel orderChangeMmModel = new OrderChangeMmModel();
			BeanUtils.copyProperties(purchaseSupplyDealMm, orderChangeMmModel);
			orderChangeMmModel.setOrdId(orderChangeModel.getOrdId());
			orderChangeMmModel.setOrdCode("");
			orderChangeMmModel.setOrdName("");
			orderChangeMmModel.setStatus(Global.NO + "");
			orderChangeMmModel.setResId(ordId);
			orderChangeMmModel.setResCode1(orderModel.getOrdCode());
			orderChangeMmModel.setCreateTime(DateUtils.getCurrentTime());
			orderChangeMmDao.insert(orderChangeMmModel);
		}

		HttpResult httpResult = new HttpResult();
		if (result > 0) {
			httpResult.setMsg("生成成功！");
		} else {
			httpResult.setMsg("生成失败！");
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
		}
		return httpResult;
	}

	/**
	 * 撤回
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult back(String ordId) {
		if (!StringUtils.isNotNull(ordId)) {
			return HttpResult.error("参数不能为空");
		}
		OrderChangeModel orderChangeModel = orderChangeDao.load(ordId);
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (StringUtils.isNotNull(orderChangeModel.getOaFlowId() + "")) {
			// oa退回才可撤回
			HttpResult httpResult = wfStatusService.getWorkflowRequestLogs(sysUser.getWxid(),
					WorkFlowIdModel.puchaseContractString, orderChangeModel.getOaFlowId() + "");
			if (httpResult.getCode() != HttpStatus.SUCCESS_CODE) {
				return httpResult;
			}
		}

		HashMap<String, Object> hashMap = new HashMap();
		hashMap.put("ordId", orderChangeModel.getOrdId());
		List<ContractChangeModel> list = contractChangeDao.selectList(hashMap);
		if (list != null && list.size() > 0) {
			return HttpResult.error("请先在变更生效删除合同！");
		}

		HttpResult httpResult = new HttpResult();
		orderChangeModel.setStatus(Global.NO + "");
		orderChangeModel.setOaFlowId(0);
		int result = orderChangeDao.update(orderChangeModel);
		if (result > 0) {
			httpResult.setMsg("撤回成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 导出
	 * 
	 * @param queryMap
	 * @param response
	 */
	public void export(Map<String, Object> queryMap, HttpServletResponse response) {
		List<OrderChangeModel> list = orderChangeDao.selectList(queryMap);
		logger.info("export:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), OrderChangeModel.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}
}
